import '@wangeditor/editor/dist/css/style.css';
import { useState, useEffect } from 'react';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import { IDomEditor, IEditorConfig } from '@wangeditor/editor';
import editorStyle from './style.less';
import { MyEditorAPI } from './type';

export const MyEditor: React.FC<MyEditorAPI.IMyEditor> = ({
  bodyHeight,
  editorForm, //表单form
  formName,
  editorValue,
}) => {
  // 存储 editor 实例
  const [editor, setEditor] = useState<IDomEditor | null>(null);

  // 编辑器内容
  const [html, setHtml] = useState('');

  const toolbarConfig = {};
  // const editorConfig: Partial<IEditorConfig> = {
  const editorConfig: any = {
    placeholder: '请输入内容...',
    MENU_CONF: {},
  };

  /**
   * 处理base64图片
   */
  editorConfig.MENU_CONF['uploadImage'] = {
    server: '',
    base64LimitSize: 100 * 1024 * 1024, // 100 兆
  };

  // 及时销毁 editor，重要！
  useEffect(() => {
    return () => {
      if (editor == null) return;
      editor.destroy();
      setEditor(null);
    };
  }, [editor]);

  useEffect(() => {
    if (editorValue) {
      setHtml(editorValue);
    }
  }, [editorValue]);

  return (
    <>
      <div
        className={editorStyle['editorStyles']}
        style={{ border: '1px solid #ccc', zIndex: 100 }}
      >
        <Toolbar
          editor={editor}
          defaultConfig={toolbarConfig}
          mode="default"
          style={{ borderBottom: '1px solid #ccc' }}
        />
        <Editor
          defaultConfig={editorConfig}
          value={html}
          onCreated={setEditor}
          onChange={(editor) => {
            let editorHtme = editor.getHtml();
            let editorText = editor.getText();
            /**
             * 判断是否输入值了,
             */
            if (editorHtme == '<p><br></p>') {
              editorForm?.setFieldsValue({ [formName]: undefined });
            } else {
              let editorJson = {
                contentText: editorText,
                contentHtml: editorHtme,
              };
              editorForm?.setFieldsValue({ [formName]: editorJson });
            }
            setHtml(editor.getHtml());
          }}
          mode="default"
          style={{ height: bodyHeight }}
        />
      </div>
    </>
  );
};
